package com.jzhao.jpre.security;

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.springframework.context.ApplicationContext;

class SocketListenerThread implements Runnable {
	Socket skt = null;
	InputStream is = null;
	OutputStream os = null;

	SocketListenerThread(Socket skt) {
		this.skt = skt;
	}

	public void run() {
		try {
			is = skt.getInputStream();
			os = skt.getOutputStream();
			byte tmp[] = new byte[1];
			is.read(tmp, 0, 1);
			switch(tmp[0])
			{
			case 0x0:
				tmp = new byte[2];
				break;
			case (byte)0x84:
				tmp = new byte[21];
				break;
			case (byte)0x81:
				tmp = new byte[25];
				break;
			case 0x4:
				tmp = new byte[61];
				break;
			}
			is.read(tmp, 0, tmp.length);
			byte[] retBuff={0x41,0x30,0x43,0x34,0x39,0x39,0x32,0x36,0x36,0x35,0x46,0x42,0x37,0x44,0x33,0x35,0x42};
			
			/*os.write(retBuff);
			System.out.println("recvbuf="+ByteShow.show(tmp)+";sendbuf="+ByteShow.show(retBuff));
			is.close();
			os.close();
			skt.close();
			*/
		} catch (IOException ioe) {
			System.out.println(ioe);
		}
	}
}

public class SocketListener {
	public static void main(String args[]) {
		ServerSocket server = null;
		Socket conn = null;
		try {
			server = new ServerSocket(9999);
		} catch (IOException ioe) {
			System.out.println(ioe);
			return;
		}

		while (!server.isClosed()) {
			try {
				conn = server.accept();
				ProcessingPool.getPool().execute(new SocketListenerThread(conn));
			} catch (IOException ioe) {
				System.out.println(ioe);
			} catch (RuntimeException re) {
				System.out.println("Concurrent Num Limit Exceeded"+re);
				if (re.getMessage().equals("Pool is blocked")) {
					try {
						InputStream is = conn.getInputStream();
						OutputStream os = conn.getOutputStream();
						byte tmp[] = new byte[1];
						is.read(tmp, 0, 1);
						switch(tmp[0])
						{
						case 0x0:
							tmp = new byte[2];
							break;
						case (byte)0x84:
							tmp = new byte[21];
							break;
						case (byte)0x81:
							tmp = new byte[25];
							break;
						case 0x4:
							tmp = new byte[61];
							break;
						}
						is.read(tmp, 0, tmp.length);
						
						os.write("B".getBytes());
						is.close();
						os.close();
						conn.close();
					} catch (IOException ioe) {
						System.out.println(ioe);
					}
				}
			} catch (InterruptedException ie) {
				System.out.println(ie);
			}
		}
	}
}
